import 'dart:async';
import 'dart:developer';

import 'package:audioplayers/audioplayers.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:lyps_music/request/index.dart';
import 'package:lyps_music/store/index.dart';
import 'package:provider/provider.dart';

/// 主页的控制面板
class HomeControl extends StatefulWidget {
  const HomeControl({super.key});

  @override
  State<StatefulWidget> createState() => _HomeControlState();
}

class _HomeControlState extends State<HomeControl> {
  AudioPlayer? audioPlayer;
  Duration duration = const Duration(seconds: 1);
  Duration current = Duration.zero;
  late StreamSubscription<Duration> positionHandle;
  late StreamSubscription<Duration> durationHandle;
  bool showMediaImgModel = false;
  String get timeLabel {
    var dm = duration.inMinutes > 9 ? duration.inMinutes : '0${duration.inMinutes}';
    var cm = current.inMinutes > 9 ? current.inMinutes : '0${current.inMinutes}';
    var ds = duration.inSeconds % 60 > 9 ? duration.inSeconds % 60 : '0${duration.inSeconds % 60}';
    var cs = current.inSeconds % 60 > 9 ? current.inSeconds % 60 : '0${current.inSeconds % 60}';
    return "$dm:$ds/$cm:$cs";
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      // ignore: use_build_context_synchronously
      audioPlayer = context.read<Store>().audioplayer;
      positionHandle = audioPlayer!.onPositionChanged.listen((onData) {
        setState(() {
          current = onData;
        });
      });
      durationHandle = audioPlayer!.onDurationChanged.listen((onData) {
        setState(() {
          duration = onData;
        });
      });
    });
  }

  @override
  void dispose() {
    positionHandle.cancel();
    durationHandle.cancel();
    super.dispose();
  }

  Widget _showMediaImage(String? path) {
    if (path == null) return Image.asset("assets/images/cover.jpg", width: 60, height: 60);
    return Image.network(MyRequest.dio.options.baseUrl + path, width: 60, height: 60);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          LayoutBuilder(
            builder: (context, constraints) {
              return MouseRegion(
                cursor: SystemMouseCursors.click,
                child: GestureDetector(
                  onTapUp: (details) {
                    var pos = details.localPosition.dx / constraints.maxWidth * duration.inMilliseconds;
                    audioPlayer?.seek(Duration(milliseconds: pos.toInt()));
                  },
                  child: Container(
                    width: double.infinity,
                    height: 5,
                    alignment: Alignment.centerLeft,
                    margin: const EdgeInsets.symmetric(vertical: 5),
                    decoration: BoxDecoration(color: Colors.grey, borderRadius: BorderRadius.circular(5)),
                    child: Container(
                      width: (current.inSeconds / (duration.inSeconds == 0 ? 1 : duration.inSeconds)) * constraints.maxWidth,
                      decoration: BoxDecoration(color: Colors.green, borderRadius: BorderRadius.circular(5)),
                    ),
                  ),
                ),
              );
            },
          ),
          Row(
            children: [
              Selector<Store, dynamic>(
                selector: (p0, p1) => p1.currentMusic,
                builder: (context, value, child) {
                  return Row(
                    children: [
                      MouseRegion(
                        cursor: SystemMouseCursors.click,
                        onEnter: (event) {
                          setState(() {
                            showMediaImgModel = true;
                          });
                        },
                        onExit: (event) {
                          setState(() {
                            showMediaImgModel = false;
                          });
                        },
                        child: Stack(
                          children: [
                            Container(
                              decoration: BoxDecoration(borderRadius: BorderRadius.circular(5)),
                              clipBehavior: Clip.antiAlias,
                              child: _showMediaImage(value['media_image']),
                            ),
                            Visibility(
                              visible: showMediaImgModel,
                              child: Positioned.fill(
                                child: GestureDetector(
                                  onTap: () {
                                    AutoRouter.of(context).pushNamed('/info');
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(5), color: Colors.black.withOpacity(0.3)),
                                    clipBehavior: Clip.antiAlias,
                                    child: Icon(IconData(0xec0b, fontFamily: 'iconfont'), color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(width: 10),
                      SizedBox(
                        height: 60,
                        width: 150,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(value['name'], style: TextStyle(color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis),
                            Text(value['id3'] != null ? value['id3']['ID3V1']['author'] : '未知', style: TextStyle(color: Colors.grey, fontSize: 12)),
                            Row(
                              children: [
                                Icon(IconData(0xe7aa, fontFamily: 'iconfont'), color: Colors.white, size: 15),
                                SizedBox(width: 10),
                                Icon(IconData(0xe6bc, fontFamily: 'iconfont'), color: Colors.white, size: 15),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                },
              ),
              Expanded(
                child: Row(
                  children: [
                    SizedBox(width: 100),
                    Icon(IconData(0xe63c, fontFamily: 'iconfont'), color: Colors.white),
                    SizedBox(width: 10),
                    Visibility(
                      visible: audioPlayer == null || audioPlayer!.state != PlayerState.playing,
                      child: MouseRegion(
                        cursor: SystemMouseCursors.click,
                        child: GestureDetector(
                          onTap: () {
                            var currentMusic = context.read<Store>().currentMusic;
                            if (currentMusic != null) audioPlayer?.play(UrlSource("${MyRequest.dio.options.baseUrl}${currentMusic['path']}"));
                          },
                          child: Icon(IconData(0xe629, fontFamily: 'iconfont'), size: 50, color: Colors.white),
                        ),
                      ),
                    ),
                    Visibility(
                      visible: audioPlayer != null && audioPlayer!.state == PlayerState.playing,
                      child: MouseRegion(
                        cursor: SystemMouseCursors.click,
                        child: GestureDetector(
                          onTap: () {
                            var currentMusic = context.read<Store>().currentMusic;
                            if (currentMusic != null) audioPlayer?.pause();
                          },
                          child: Icon(IconData(0xe679, fontFamily: 'iconfont'), size: 50, color: Colors.white),
                        ),
                      ),
                    ),
                    SizedBox(width: 10),
                    Icon(IconData(0xe63e, fontFamily: 'iconfont'), color: Colors.white),
                  ],
                ),
              ),
              Text(timeLabel, style: TextStyle(color: Colors.white))
            ],
          ),
          const SizedBox(height: 10),
        ],
      ),
    );
  }
}
